package activity

import android.graphics.Color
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.TypedValue
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import cn.pedant.SweetAlert.SweetAlertDialog
import com.hontech.kdxclient.R
import event.*
import ext.log
import manager.AppManager
import manager.ReplenishManager
import manager.TaskManager
import manager.WaresManager
import mvc.model.inventory.ScanGoodsType
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import popup.ReplenishScanWindow
import protocol.BaseProtocol
import serialport.DeliverPortManager
import task.ReplenishCompleteTask
import task.ReplenishListTask
import task.UpdateGoodsTypeInfoTask


class ScanActivity : AppCompatActivity() {
    companion object {
        var isShow = false
    }

    private val scanRecyclerView: RecyclerView by lazy { findViewById<RecyclerView>(R.id.id_scan_recycler_view_goods_type_scan) }
    private val replenishRecyclerView: RecyclerView by lazy { findViewById<RecyclerView>(R.id.id_scan_recycler_view_replenish) }
    private val clearRecyclerView: RecyclerView by lazy { findViewById<RecyclerView>(R.id.id_scan_recycler_view_clear) }
    private val serverRecyclerView: RecyclerView by lazy { findViewById<RecyclerView>(R.id.id_scan_recycler_view_goods_type_server) }
    private val scanButton: Button by lazy { findViewById<Button>(R.id.id_scan_button_scan) }
    private val replenishButton: Button by lazy { findViewById<Button>(R.id.id_scan_button_replenish) }
    private val completionButton: Button by lazy { findViewById<Button>(R.id.id_scan_button_replenish_completion) }
    private val quitButton: Button by lazy { findViewById<Button>(R.id.id_scan_button_quit) }
    private val textViewReplenish: TextView by lazy { findViewById<TextView>(R.id.id_scan_text_view_replenish) }
    private val textViewClear: TextView by lazy { findViewById<TextView>(R.id.id_scan_text_view_clear) }
    private val replenishScanButton: Button by lazy { findViewById<Button>(R.id.id_scan_button_scan_replenish) }
    private val replenishAdapter = ReplenishAdapter()
    private val clearAdapter = ClearAdapter()
    private val scanAdapter = ScanAdapter()
    private val serverConfigAdapter = ServerConfigAdapter()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_scan)
        quitButton.setOnClickListener(::onClickQuit)
        replenishButton.setOnClickListener(::onClickReplenishList)
        completionButton.setOnClickListener(::onClickReplenishCompletion)
        scanButton.setOnClickListener(::onClickScan)
        replenishScanButton.setOnClickListener(::onClickReplenishScan)

        replenishRecyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        replenishRecyclerView.adapter = replenishAdapter
        clearRecyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        clearRecyclerView.adapter = clearAdapter
        scanRecyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        scanRecyclerView.adapter = scanAdapter
        serverRecyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        serverRecyclerView.adapter = serverConfigAdapter

        textViewClear.visibility = View.GONE
        textViewReplenish.visibility = View.GONE
    }

    override fun onStart() {
        super.onStart()
        EventBus.getDefault().register(this)
    }

    override fun onStop() {
        super.onStop()
        EventBus.getDefault().unregister(this)
    }

    override fun onPause() {
        isShow = false
        super.onPause()
    }

    override fun onResume() {
        isShow = true
        super.onResume()
    }

    override fun onDestroy() {
        super.onDestroy()
        AppManager.isBusy = false
    }

    private fun onCompareError() {
        val dialog = SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE)
            .setTitleText("异常")
            .setContentText("货道扫描结果和后台不匹配")
        dialog.setCancelButton("取消") {
            dialog.cancel()
        }
        dialog.setConfirmButton("重新扫描") {
            onClickScan(scanButton)
            dialog.cancel()
        }
        dialog.setCancelable(true)
        val window = dialog.window
        val lp = window!!.attributes
        lp.gravity = Gravity.CENTER
        window.attributes = lp
        dialog.show()
    }

    private fun onCompare() {
        val rows = ReplenishManager.GoodsTypeInfo.size
        for (i in 0 until rows) {
            val cols = ReplenishManager.getColsWithRow(i + 1)
            if (cols != ReplenishManager.GoodsTypeInfo[i]) {
                onCompareError()
                return
            }
        }
        onClickReplenishList(replenishButton)
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onServerConfigGoodsTypeChangedEvent(env: ServerConfigGoodsTypeChangedEvent) {
        if (ReplenishManager.GoodsTypeInfo.size <= 0) {

            val dialog = SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE)
            dialog.setCancelable(true)
            dialog.setCancelButton("取消") {
                dialog.cancel()
            }
            val window = dialog.window
            val lp = window!!.attributes
            lp.gravity = Gravity.CENTER
            window.attributes = lp
            dialog.titleText = "网络错误"
            dialog.contentText = "无法获取货道配置"
            return
        }
        serverConfigAdapter.notifyDataSetChanged()
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onInventoryChangedEvent(env: InventoryChangedEvent) {
        Toast.makeText(this, "商品库存已经重新更新", Toast.LENGTH_SHORT).show()
        textViewReplenish.visibility = View.VISIBLE
        replenishRecyclerView.visibility = View.GONE
        textViewReplenish.setTextColor(Color.RED)
        textViewReplenish.text = "商品已经更新"
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onReplenishListChangedEvent(env: ReplenishListChangedEvent) {
        if (env.result) {
            textViewReplenish.setTextColor(Color.GRAY)
            if (ReplenishManager.ReplenishList.isEmpty()) {
                textViewReplenish.visibility = View.VISIBLE
                replenishRecyclerView.visibility = View.GONE
                textViewReplenish.text = "补入清单为空"
            } else {
                textViewReplenish.visibility = View.GONE
                replenishRecyclerView.visibility = View.VISIBLE
                replenishAdapter.notifyDataSetChanged()
            }

            if (ReplenishManager.ClearList.isEmpty()) {
                textViewClear.visibility = View.VISIBLE
                clearRecyclerView.visibility = View.GONE
            } else {
                textViewClear.visibility = View.GONE
                clearRecyclerView.visibility = View.VISIBLE
                clearAdapter.notifyDataSetChanged()
            }

            return
        }
        Toast.makeText(this, "获取补货清单失败", Toast.LENGTH_SHORT).show()
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onReplenishCompleteEvent(env: ReplenishCompleteEvent) {
        if (env.result) {
            /**
             * 补货完成 就重新扫描库存
             */
            val buf = BaseProtocol(0x05)
                .build()
            DeliverPortManager.Instance.write(buf)
            return
        }
        Toast.makeText(this, "补货完成失败", Toast.LENGTH_SHORT).show()
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onScanResultEvent(env: ScanResultEvent) {
        if (env.isFinish() || env.isError()) {
            onCompare()
            return
        }
        val item = ScanGoodsType(env.row, env.col)
        ReplenishManager.ScanGoodsType.add(item)
        scanAdapter.notifyItemChanged(ReplenishManager.ScanGoodsType.size - 1)
        scanRecyclerView.scrollToPosition(ReplenishManager.ScanGoodsType.size - 1)
        serverConfigAdapter.notifyDataSetChanged()
    }

    private fun onClickQuit(view: View) {
        finish()
    }

    private fun onClickReplenishList(view: View) {
        TaskManager.AsyncHandler.post(ReplenishListTask())
        Toast.makeText(this, "开始获取补货清单", Toast.LENGTH_SHORT).show()
    }

    private fun onClickReplenishCompletion(view: View) {
        TaskManager.AsyncHandler.post(ReplenishCompleteTask())
        Toast.makeText(this, "发送补货完成请求", Toast.LENGTH_SHORT).show()
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onDeliveryScanResultEvent(env: DeliveryScanResultEvent) {
        log("库存扫码结果-${env.state}")
        if (env.isFinish()) {
            log("开始同步库存")
            TaskManager.UiHandler.postDelayed({
                WaresManager.refreshAsync()
            }, 10 * 1000)
        }
    }

    private fun onClickScan(view: View) {
        ReplenishManager.ScanGoodsType.clear()
        val buf = BaseProtocol(0x03)
            .build()
        DeliverPortManager.Instance.write(buf)

        TaskManager.DelayHandler.post(UpdateGoodsTypeInfoTask())
    }

    private fun onClickReplenishScan(view: View) {
        ReplenishScanWindow.Instance.show(view)
    }

    /**
     * 后台的货道配置
     */
    private class ServerConfigItemView(view: View) : RecyclerView.ViewHolder(view) {
        private val textView = view.findViewById<TextView>(R.id.id_item_scan_text_view_goods_type)

        fun set(position: Int) {
            val info = ReplenishManager.GoodsTypeInfo[position]
            textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, 20f)
            textView.text = "第${position + 1}行:配置了${info}列,扫描到了${ReplenishManager.getColsWithRow(position + 1)}列"
        }
    }

    private class ServerConfigAdapter : RecyclerView.Adapter<ServerConfigItemView>() {
        override fun onBindViewHolder(p0: ServerConfigItemView, p1: Int) {
            p0.set(p1)
        }

        override fun onCreateViewHolder(p0: ViewGroup, p1: Int): ServerConfigItemView {
            val view = LayoutInflater.from(p0.context).inflate(R.layout.item_scan_result, p0, false)
            return ServerConfigItemView(view)
        }

        override fun getItemCount(): Int {
            return ReplenishManager.GoodsTypeInfo.size
        }
    }

    /**
     * 扫描货道结果展示
     */
    private class ScanItemView(view: View) : RecyclerView.ViewHolder(view) {
        private val textView = view.findViewById<TextView>(R.id.id_item_scan_text_view_goods_type)

        fun set(position: Int) {
            val info = ReplenishManager.ScanGoodsType[position]
            textView.text = "${info.row}-${info.col}"
        }
    }

    private class ScanAdapter : RecyclerView.Adapter<ScanItemView>() {
        override fun onBindViewHolder(p0: ScanItemView, p1: Int) {
            p0.set(p1)
        }

        override fun onCreateViewHolder(p0: ViewGroup, p1: Int): ScanItemView {
            val view = LayoutInflater.from(p0.context).inflate(R.layout.item_scan_result, p0, false)
            return ScanItemView(view)
        }

        override fun getItemCount(): Int {
            return ReplenishManager.ScanGoodsType.size
        }
    }

    /**
     * 补货清单展示
     */
    private class ReplenishItemView(view: View) : RecyclerView.ViewHolder(view) {
        private val textViewName = view.findViewById<TextView>(R.id.id_item_text_view_name)
        private val textViewGoodsType = view.findViewById<TextView>(R.id.id_item_text_view_goods_type)
        private val textViewPlan = view.findViewById<TextView>(R.id.id_item_text_view_plan)
        private val textViewReality = view.findViewById<TextView>(R.id.id_item_text_view_reality)
        private val buttonAdd = view.findViewById<Button>(R.id.id_item_button_add)
        private val buttonReduce = view.findViewById<Button>(R.id.id_item_button_reduce)

        fun set(position: Int) {
            val info = ReplenishManager.ReplenishList[position]
            textViewName.text = info.name
            textViewGoodsType.text = info.goodsTypeName
            textViewPlan.text = "应补:${info.planNumber}"
            textViewReality.text = "实补:${info.realityNumber}"
            buttonAdd.setOnClickListener {
                if (info.realityNumber >= info.planNumber) {
                    return@setOnClickListener
                }
                info.realityNumber++
                textViewReality.text = "实补:${info.realityNumber}"
            }
            buttonReduce.setOnClickListener {
                if (info.realityNumber <= 0) {
                    return@setOnClickListener
                }
                info.realityNumber--
                textViewReality.text = "实补:${info.realityNumber}"
            }
        }
    }

    private class ReplenishAdapter : RecyclerView.Adapter<ReplenishItemView>() {
        override fun getItemCount(): Int {
            return ReplenishManager.ReplenishList.size
        }

        override fun onBindViewHolder(p0: ReplenishItemView, p1: Int) {
            p0.set(p1)
        }

        override fun onCreateViewHolder(p0: ViewGroup, p1: Int): ReplenishItemView {
            val view = LayoutInflater.from(p0.context)
                .inflate(R.layout.item_replenish, p0, false)
            return ReplenishItemView(view)
        }
    }

    private class ClearItemView(view: View) : RecyclerView.ViewHolder(view) {
        private val textViewName = view.findViewById<TextView>(R.id.id_item_text_view_name)
        private val textViewGoodsType = view.findViewById<TextView>(R.id.id_item_text_view_goods_type)
        private val textViewNumber = view.findViewById<TextView>(R.id.id_item_text_view_number)
        private val textViewPastdue = view.findViewById<TextView>(R.id.id_item_text_view_past_due)

        fun set(position: Int) {
            val info = ReplenishManager.ClearList[position]
            textViewName.text = info.name
            textViewGoodsType.text = info.goodsTypeName
            textViewNumber.text = "数量:${info.number}"
            textViewPastdue.text = if (info.pastdue == "是") "已经过期" else "未过期"
        }
    }

    private class ClearAdapter : RecyclerView.Adapter<ClearItemView>() {
        override fun getItemCount(): Int {
            return ReplenishManager.ClearList.size
        }

        override fun onBindViewHolder(p0: ClearItemView, p1: Int) {
            p0.set(p1)
        }

        override fun onCreateViewHolder(p0: ViewGroup, p1: Int): ClearItemView {
            val view = LayoutInflater.from(p0.context)
                .inflate(R.layout.item_clear, p0, false)
            return ClearItemView(view)
        }
    }
}









